import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

service.interceptors.request.use(config => {
  // 请求拦截器可以拦截到当前正在发送的请求, 获取到的参数, 是当前发送请求的设定
  if (store.state.user.token) {
    const timeout = 60 * 1000 * 10
    const logintime = localStorage.getItem('logintime')
    if (Date.now() - logintime > timeout) {
      store.dispatch('user/logout')
      router.push('/login')
      // return Promise.reject(new Error('token超时'))
    }
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
})

service.interceptors.response.use(res => {
  const { success, message } = res.data
  if (success) {
    return res.data.data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err.response && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  console.log(err)
  Message.error('网络错误')
  return Promise.reject(new Error('网络错误'))
})

export default service
